package c.main.web;

import c.main.core.C;
import c.main.core.IAuthorization;
import c.main.domain.LoginUser;
import c.main.jdbc.JdbcTemplate;
import c.main.service.SysService;
import c.main.util.WebUtils;
import c.main.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Author: chengwei
 * Date:   2016/3/15
 * Time:   10:44
 */
@WebFilter(
        urlPatterns = {WebUtils.LOGIN_FILTER_PREFIX_NAME + "/*"},
        initParams = {
                @WebInitParam(name = "loginUrl",value = "/login.action"),
                @WebInitParam(name = "adminLoginUrl",value = "/adminlogin.action")
        }
)
public class UserLoginFilter implements Filter{
    private String loginUrl;
    private FilterConfig config;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
        this.loginUrl = config.getInitParameter("loginUrl");
        if (StringUtils.isNullOrEmpty(loginUrl)) {
            throw new RuntimeException("系统未指定登录页面地址!");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpSession session = request.getSession(false);
        LoginUser user = null;
        if (session == null || (user = (LoginUser) session.getAttribute(IAuthorization.SESSION_KEY)) == null) {
            ((HttpServletResponse) servletResponse).sendRedirect(loginUrl);
        }
        
        if (user != null) {
            SysService service = C.getBean(SysService.class);
            boolean hasAction = service.hasAction(user,request.getParameter(WebUtils.ACTION_NAME));
            if (!hasAction) {
                ((HttpServletResponse) servletResponse).sendRedirect(loginUrl);
                throw new RuntimeException("您不能访问此地址!!!");
            }
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            ((HttpServletResponse) servletResponse).sendRedirect(loginUrl);
        }
    }

    @Override
    public void destroy() {
        loginUrl = null;
        config = null;
    }
}
